package br.com.winesys.geta.persistence.hibernate;

import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.ejb.Ejb3Configuration;

public final class HibernateSessionFactoryBuilder {

	private static Map<String, SessionFactory> factories = new TreeMap<String, SessionFactory>();

	public static void configure(String persistenceUnit, Properties properties) {
		final AnnotationConfiguration cfg = new AnnotationConfiguration();
		cfg.configure(HibernateSessionFactoryBuilder.class.getResource(String.format("/%s.hibernate.cfg.xml", persistenceUnit)));
		cfg.setProperties(properties);
		final SessionFactory sessionFactory = cfg.buildSessionFactory();
		HibernateSessionFactoryBuilder.factories.put(persistenceUnit, sessionFactory);
	}

	public static void configureFromJPA(String persistenceUnit, Properties properties) {
		final TreeMap<Object, Object> map = new TreeMap<Object, Object>();
		if (properties != null) {
			for (final Object key : properties.keySet()) {
				map.put(key, properties.get(key));
			}
		}
		final AnnotationConfiguration cfg = new Ejb3Configuration().configure(persistenceUnit, map).getHibernateConfiguration();
		final SessionFactory sessionFactory = cfg.buildSessionFactory();
		HibernateSessionFactoryBuilder.factories.put(persistenceUnit, sessionFactory);
	}

	public static SessionFactory getSessionFactory(String persistenceUnit) {
		final SessionFactory sessionFactory = HibernateSessionFactoryBuilder.factories.get(persistenceUnit);
		if (sessionFactory == null) {
			throw new RuntimeException(String.format("No session factory configured for persistence unit: %s", persistenceUnit));
		}
		return sessionFactory;
	}
}